package com.jgraph.pad.persistence;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.Properties;

import com.jgraph.editor.persistence.JGraphPersistenceManagerFactoryMethod;

/**
 * This class defines a persistence manager that handles (reads/writes)
 * byte arrays.
 *
 * @author svetoslavganov@mail.utexas.edu
 *
 */
public class JGraphpadByteArrayPersistenceManager
        extends JGraphpadAbstractPersistenceManager<byte[]> {

    /**
     * Raw byte array file type.
     */
    public static final String TYPE_BYTE_ARRAY = "ByteArray";

	/**
	 * All supported file types by this persistence manager.
	 */
    public static final String[] SUPPORTED_FILE_TYPES =
    	new String[] {TYPE_BYTE_ARRAY};

	@Override
	public byte[] readObject(String uri) throws MalformedURLException,
			IOException {
		InputStream in = getInputStream(uri);
		int length = (int) new File(uri).length();
		byte[] bytes = new byte[length];

		int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
                && (numRead = in.read(bytes, offset, length - offset)) >= 0) {
            offset += numRead;
        }
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file " + uri);
        }
		return bytes;
	}

	@Override
	public void writeObject(byte[] object, String uri)
			throws MalformedURLException, IOException {
		OutputStream out = getOutputStream(uri);
		if (out == null) {
			return;
		}
		out.write((byte[]) object);
		out.flush();
		out.close();
	}

	/**
	 * Factory method for {@link JGraphpadByteArrayPersistenceManager}s.
	 */
	public static class FactoryMethod
        extends JGraphPersistenceManagerFactoryMethod<byte[]> {

        public FactoryMethod(Properties properties) {
	        super(SUPPORTED_FILE_TYPES, properties);
        }

        public JGraphpadAbstractPersistenceManager<byte[]>
                createPersistenceManager(Properties properties) {
	         return new JGraphpadByteArrayPersistenceManager();
        }
    }
}
